package and.process;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import and.common.MyCommon;
import and.tools.FileHelper;

public class StatisticsProcess {
	public String getMostNum() {
		StringBuilder result = new StringBuilder();
		try {
			if(FileHelper.isFileExist(MyCommon.FILEPATH
					+ MyCommon.StatisticsFile)){
				String dataStr = FileHelper.read(MyCommon.FILEPATH
						+ MyCommon.StatisticsFile, "utf-8");
				String[] datas = dataStr.split("\n");
				MyCommon.QishuCount = datas.length;
				Map<String, Integer> map = new HashMap<String, Integer>();
				Integer tempInt;
				String[] nums;
				for (int i = 0; i < datas.length; i++) {
					
					nums = datas[i].split(";")[3].split(" ");
					for (int j = 0; j < nums.length; j++) {
						
						if (map.containsKey(nums[j])) {
							tempInt = map.get(nums[j]);
							map.put(nums[j], tempInt + 1);
						} else {
							map.put(nums[j], 1);
						}
					}
				}

				ByValueComparator bvc = new ByValueComparator(map);
				TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(
						bvc);
				sorted_map.putAll(map);

				for (String name : sorted_map.keySet()) {
					result.append(name);
					result.append("=");
					result.append(map.get(name));
					result.append("\n");
				}
				return result.toString();
			}else{
				QueryProcess query =new QueryProcess();
				query.query();
				return this.getMostNum();
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("统计最多出现时出错！");
			return null;
		}

	}

	static class ByValueComparator implements Comparator<String> {
		Map<String, Integer> base_map;

		public ByValueComparator(Map<String, Integer> base_map) {
			this.base_map = base_map;
		}

		public int compare(String arg0, String arg1) {
			if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {
				return 0;
			}
			if (base_map.get(arg0) < base_map.get(arg1)) {
				return 1;
			} else if (base_map.get(arg0) == base_map.get(arg1)) {
				return 1;
			} else {
				return -1;
			}
		}
	}

}
